<?php

namespace App\Http\Controllers\Service;

use App\Http\Controllers\Controller;
use App\Models\M3Result;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;

class CartController extends Controller
{

    public function addCart($product_id,Request $request)
    {
        $bk_cart = $request->cookie('bk_cart');

        $bk_cart_arr = ($bk_cart != null?explode(',',$bk_cart) : array());



        $count = 0;
        $flag = false;
        foreach ($bk_cart_arr as &$value) {
            $index = strpos($value, ':');

            if ( substr($value,0,$index) == $product_id ) {
               $count = (int) substr($value, $index+1) + 1;
               $value = substr($value,0,$index + 1).$count;
               $flag = true;
               break;
            }

        }

        if (!$flag) {
            $count++;
            $bk_cart_arr[] = $product_id . ':' . $count;
        }

        $bk_cart = implode(',', $bk_cart_arr);


        $m3Result = new M3Result();

        $m3Result->status = 0;
        $m3Result->message = '添加成功';
        return response()->json($m3Result)->withCookie('bk_cart',$bk_cart);
    }


    public function deleteCart(Request $request)
    {
        $m3Result = new M3Result();
        $product_ids = $request->input('product_ids','');

        if ($product_ids == '') {
            $m3Result->status = 1;
            $m3Result->message = '删除失败';
            return $m3Result->toJson();
        }

        $product_ids_arr = explode(',', $product_ids);

        $bk_cart = $request->cookie('bk_cart');

        $bk_cart_arr = ( $bk_cart == null?
            array() : explode(',',$bk_cart));

        foreach ($bk_cart_arr as $key=>$value) {

            $index = strpos($value,':');
            $product_id = substr($value,0,$index);

            if (in_array($product_id,$product_ids_arr)) {
                array_splice($bk_cart_arr,$key,1);
            }

        }

        $bk_cart = implode(',',$bk_cart_arr);

        $m3Result->status = 0;
        $m3Result->message = '删除成功';
        return response($m3Result->toJson())->withCookie('bk_cart',$bk_cart);
    }
}
